package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yuoj.annotation.AuthCheck;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.constant.UserConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.dto.membershipplan.MembershipPlanAddRequest;
import com.yupi.yuoj.model.dto.membershipplan.MembershipPlanEditRequest;
import com.yupi.yuoj.model.dto.membershipplan.MembershipPlanQueryRequest;
import com.yupi.yuoj.model.dto.membershipplan.MembershipPlanUpdateRequest;
import com.yupi.yuoj.model.entity.MembershipPlan;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.model.vo.MembershipPlanVO;
import com.yupi.yuoj.service.MembershipPlanService;
import com.yupi.yuoj.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 会员套餐接口
 *
 * @author jingjin
 */
@RestController
@RequestMapping("/membership_plan")
@Slf4j
public class MembershipPlanController {

    @Resource
    private MembershipPlanService membershipPlanService;

    @Resource
    private UserService userService;

    /**
     * 创建会员套餐
     *
     * @param membershipPlanAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<String> addMembershipPlan(@RequestBody MembershipPlanAddRequest membershipPlanAddRequest, HttpServletRequest request) {
        if (membershipPlanAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        MembershipPlan membershipPlan = new MembershipPlan();
        BeanUtils.copyProperties(membershipPlanAddRequest, membershipPlan);
        membershipPlanService.validMembershipPlan(membershipPlan, true);
        User loginUser = userService.getLoginUser(request);
        // MembershipPlan实体没有userId字段，移除此行
        // membershipPlan.setUserId(loginUser.getId());
        boolean result = membershipPlanService.save(membershipPlan);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        String newMembershipPlanId = membershipPlan.getId();
        return ResultUtils.success(newMembershipPlanId);
    }

    /**
     * 删除会员套餐
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteMembershipPlan(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String id = String.valueOf(deleteRequest.getId());
        // 判断是否存在
        MembershipPlan oldMembershipPlan = membershipPlanService.getById(id);
        ThrowUtils.throwIf(oldMembershipPlan == null, ErrorCode.NOT_FOUND_ERROR);
        boolean b = membershipPlanService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新会员套餐（仅管理员）
     *
     * @param membershipPlanUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateMembershipPlan(@RequestBody MembershipPlanUpdateRequest membershipPlanUpdateRequest) {
        if (membershipPlanUpdateRequest == null || membershipPlanUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        MembershipPlan membershipPlan = new MembershipPlan();
        BeanUtils.copyProperties(membershipPlanUpdateRequest, membershipPlan);
        // 参数校验
        membershipPlanService.validMembershipPlan(membershipPlan, false);
        long id = membershipPlanUpdateRequest.getId();
        // 判断是否存在
        MembershipPlan oldMembershipPlan = membershipPlanService.getById(id);
        ThrowUtils.throwIf(oldMembershipPlan == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = membershipPlanService.updateById(membershipPlan);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<MembershipPlan> getMembershipPlanById(String id, HttpServletRequest request) {
        if (id == null || id.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        MembershipPlan membershipPlan = membershipPlanService.getById(id);
        if (membershipPlan == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(membershipPlan);
    }

    /**
     * 分页获取会员套餐列表（仅管理员）
     *
     * @param membershipPlanQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<MembershipPlan>> listMembershipPlanByPage(@RequestBody MembershipPlanQueryRequest membershipPlanQueryRequest) {
        long current = membershipPlanQueryRequest.getCurrent();
        long size = membershipPlanQueryRequest.getPageSize();
        Page<MembershipPlan> membershipPlanPage = membershipPlanService.page(new Page<>(current, size),
                membershipPlanService.getQueryWrapper(membershipPlanQueryRequest));
        return ResultUtils.success(membershipPlanPage);
    }

    /**
     * 分页获取会员套餐列表（封装类）
     *
     * @param membershipPlanQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<MembershipPlanVO>> listMembershipPlanVOByPage(@RequestBody MembershipPlanQueryRequest membershipPlanQueryRequest,
            HttpServletRequest request) {
        long current = membershipPlanQueryRequest.getCurrent();
        long size = membershipPlanQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<MembershipPlan> membershipPlanPage = membershipPlanService.page(new Page<>(current, size),
                membershipPlanService.getQueryWrapper(membershipPlanQueryRequest));
        return ResultUtils.success(membershipPlanService.getMembershipPlanVOPage(membershipPlanPage, request));
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<MembershipPlanVO> getMembershipPlanVOById(String id, HttpServletRequest request) {
        if (id == null || id.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        MembershipPlan membershipPlan = membershipPlanService.getById(id);
        if (membershipPlan == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(membershipPlanService.getMembershipPlanVO(membershipPlan, request));
    }

    /**
     * 编辑会员套餐（给用户使用）
     *
     * @param membershipPlanEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> editMembershipPlan(@RequestBody MembershipPlanEditRequest membershipPlanEditRequest, HttpServletRequest request) {
        if (membershipPlanEditRequest == null || membershipPlanEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        MembershipPlan membershipPlan = new MembershipPlan();
        BeanUtils.copyProperties(membershipPlanEditRequest, membershipPlan);
        // 参数校验
        membershipPlanService.validMembershipPlan(membershipPlan, false);
        String id = String.valueOf(membershipPlanEditRequest.getId());
        // 判断是否存在
        MembershipPlan oldMembershipPlan = membershipPlanService.getById(id);
        ThrowUtils.throwIf(oldMembershipPlan == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = membershipPlanService.updateById(membershipPlan);
        return ResultUtils.success(result);
    }

}